package com.snopy.concurrency.demo_base;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

/**
  *@description:
  *  管道输入/输出流主要包括了如下4种具体实现：PipedOutputStream、PipedInputStream、
  *  PipedReader和PipedWriter，前两种面向字节，而后两种面向字符。
  *@author:tangxiuliang
  *@date:2020/9/28 13:10
  */
@Slf4j
public class Piped {
    public static void main(String[] args) throws IOException {
        /*
        * 1.创建
        * */
        PipedWriter out = new PipedWriter();
        PipedReader in = new PipedReader();
        /*
        * 连接
        *  将输出流和输入流进行连接，否则在使用时会抛出IOException
        * */
        out.connect(in);

        Thread printThread = new Thread(new Print(in),"printThread");
        printThread.start();
        int receive = 0;
        try {
            while ((receive = System.in.read())!=-1){
                out.write(receive);
            }
        }finally {
            out.close();
        }

    }

    static class Print implements Runnable{
        PipedReader in;

        public Print(PipedReader in) {
            this.in = in;
        }

        @Override
        public void run() {
            int receive = 0;
            try {

                while((receive = in.read())!=-1){
                    System.out.print((char) receive);
                    log.info("回复：{}",(char) receive);
                }

                } catch (IOException e) {
                    e.printStackTrace();
                }


        }
    }

}
